#include "gui/main_window.h"
#include <QFileDialog>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) 
    : QMainWindow(parent) {
    setWindowTitle("CodeForge");
    resize(1024, 768);
    
    // 创建中心部件
    tabWidget = new QTabWidget(this);
    tabWidget->setTabsClosable(true);
    setCentralWidget(tabWidget);

   // 在MainWindow类中添加成员
    projectManager = new ProjectManager(this);
    // 在MainWindow构造函数中添加(补充）
    compilerManager = new CompilerManager(this);
    // 在MainWindow类中添加成员
    debugger = new GdbDebugger(this);

    // 在MainWindow构造函数中添加
    pluginManager = new PluginManager(this, this);
    pluginManager->loadPlugins();
    
    // 创建界面元素
    createMenus();
    createToolBars();
    createStatusBar();
    createEditor();
}

MainWindow::~MainWindow() {
}

void MainWindow::createMenus() {
    // 文件菜单
    fileMenu = menuBar()->addMenu("文件(&F)");
    fileMenu->addAction("新建(&N)", this, [this]() {
        createEditor();
    }, QKeySequence::New);
    
    fileMenu->addAction("打开(&O)...", this, [this]() {
        QString fileName = QFileDialog::getOpenFileName(this, "打开文件");
        if (!fileName.isEmpty()) {
            createEditor()->loadFile(fileName);
        }
    }, QKeySequence::Open);
    
    fileMenu->addSeparator();
    fileMenu->addAction("保存(&S)", this, [this]() {
        if (currentEditor) {
            currentEditor->save();
        }
    }, QKeySequence::Save);
    
    fileMenu->addAction("另存为(&A)...", this, [this]() {
        if (currentEditor) {
            currentEditor->saveAs();
        }
    });
    
    fileMenu->addSeparator();
    fileMenu->addAction("退出(&X)", qApp, &QApplication::quit, QKeySequence::Quit);
    // 添加项目菜单
    QMenu *projectMenu = menuBar()->addMenu("项目(&P)");
    projectMenu->addAction("新建项目(&N)...", this, [this]() {
    QDialog dialog(this);
    dialog.setWindowTitle("新建项目");
    
    QFormLayout *layout = new QFormLayout(&dialog);
    
    QLineEdit *nameEdit = new QLineEdit(&dialog);
    QLineEdit *pathEdit = new QLineEdit(QDir::homePath(), &dialog);
    QPushButton *browseButton = new QPushButton("浏览...", &dialog);
    QComboBox *templateCombo = new QComboBox(&dialog);
    templateCombo->addItems({"控制台应用", "GUI应用", "库"});
    
    QDialogButtonBox *buttonBox = new QDialogButtonBox(
        QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dialog);
    
    connect(browseButton, &QPushButton::clicked, this, [pathEdit]() {
        QString dir = QFileDialog::getExistingDirectory(nullptr, "选择项目目录", 
                                                     pathEdit->text());
        if (!dir.isEmpty()) {
            pathEdit->setText(dir);
        }
    });
    
    connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
    
    layout->addRow("项目名称:", nameEdit);
    layout->addRow("项目位置:", pathEdit);
    layout->addRow("", browseButton);
    layout->addRow("模板:", templateCombo);
    layout->addRow(buttonBox);
    
    if (dialog.exec() == QDialog::Accepted) {
        QString projectName = nameEdit->text().trimmed();
        QString projectPath = pathEdit->text().trimmed();
        QString templateName = templateCombo->currentText();
        
        if (projectName.isEmpty() || projectPath.isEmpty()) {
            QMessageBox::warning(this, "警告", "项目名称和位置不能为空");
            return;
        }
        
        if (projectManager->createProject(projectPath, projectName, templateName)) {
            statusBar()->showMessage("项目创建成功: " + projectName, 3000);
        } else {
            QMessageBox::warning(this, "警告", "项目创建失败");
        }
    }
    });

    projectMenu->addAction("打开项目(&O)...", this, [this]() {
    QString fileName = QFileDialog::getOpenFileName(this, "打开项目", 
                                                  QDir::homePath(), 
                                                  "CodeForge项目 (*.cforge)");
    if (!fileName.isEmpty()) {
        if (projectManager->openProject(fileName)) {
            statusBar()->showMessage("项目打开成功: " + projectManager->projectName(), 3000);
        } else {
            QMessageBox::warning(this, "警告", "无法打开项目");
        }
    }
    });

    projectMenu->addAction("关闭项目(&C)", this, [this]() {
    if (projectManager->isProjectOpen()) {
        projectManager->closeProject();
        statusBar()->showMessage("项目已关闭", 3000);
    }
});

// 连接项目信号
connect(projectManager, &ProjectManager::projectOpened, 
        this, [this](const QString &name) {
    setWindowTitle("CodeForge - " + name);
});

connect(projectManager, &ProjectManager::projectClosed, 
        this, [this]() {
    setWindowTitle("CodeForge");
});

connect(projectManager, &ProjectManager::fileAdded, 
        this, [this](const QString &filePath) {
    // 自动在编辑器中打开添加的文件
    createEditor()->loadFile(filePath);
});
    
    // 编辑菜单
    editMenu = menuBar()->addMenu("编辑(&E)");
    editMenu->addAction("撤销(&Z)", this, [this]() {
        if (currentEditor) currentEditor->undo();
    }, QKeySequence::Undo);
    
    editMenu->addAction("重做(&Y)", this, [this]() {
        if (currentEditor) currentEditor->redo();
    }, QKeySequence::Redo);
    
    editMenu->addSeparator();
    editMenu->addAction("剪切(&T)", this, [this]() {
        if (currentEditor) currentEditor->cut();
    }, QKeySequence::Cut);
    
    editMenu->addAction("复制(&C)", this, [this]() {
        if (currentEditor) currentEditor->copy();
    }, QKeySequence::Copy);
    
    editMenu->addAction("粘贴(&P)", this, [this]() {
        if (currentEditor) currentEditor->paste();
    }, QKeySequence::Paste);
    // 在编辑菜单中添加
    editMenu->addAction("查找/替换(&F)...", this, [this]() {
    if (!currentEditor) return;
    
    FindReplaceDialog *dialog = new FindReplaceDialog(currentEditor, this);
    
    connect(dialog, &FindReplaceDialog::findNext, 
            currentEditor, &CodeEditor::findNext);
    connect(dialog, &FindReplaceDialog::replace, 
            currentEditor, &CodeEditor::replace);
    connect(dialog, &FindReplaceDialog::replaceAll, 
            currentEditor, &CodeEditor::replaceAll);
    
    dialog->show();
}, QKeySequence::Find);

/ 添加插件菜单
QMenu *pluginMenu = menuBar()->addMenu("插件(&L)");
for (PluginInterface *plugin : pluginManager->plugins()) {
    pluginMenu->addAction(plugin->name());
}


    // 构建菜单
    buildMenu = menuBar()->addMenu("构建(&B)");
    buildMenu->addAction("编译(&C)", this, [this]() {
        if (currentEditor) {
            // TODO: 实现编译功能
        }
    }, QKeySequence(Qt::CTRL | Qt::Key_R));
    
    // 帮助菜单
    helpMenu = menuBar()->addMenu("帮助(&H)");
    helpMenu->addAction("关于(&A)...", this, [this]() {
        QMessageBox::about(this, "关于 CodeForge", 
            "<h2>CodeForge 0.1.0</h2>"
            "<p>跨平台代码编辑器和编译器</p>");
    });

// 添加调试菜单
QMenu *debugMenu = menuBar()->addMenu("调试(&D)");
debugMenu->addAction("开始调试(&S)", this, [this]() {
    if (!projectManager->isProjectOpen()) {
        QMessageBox::warning(this, "警告", "请先打开一个项目");
        return;
    }
    
    // 查找可执行文件
    QString buildDir = QDir(projectManager->projectPath()).absoluteFilePath("build");
    QString executable;
    
    QDirIterator it(buildDir, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        it.next();
        if (it.fileInfo().isExecutable()) {
            executable = it.filePath();
            break;
        }
    }
    
    if (executable.isEmpty()) {
        QMessageBox::warning(this, "警告", "没有找到可执行文件，请先编译项目");
        return;
    }
    
    if (debugger->start(executable, {})) {
        statusBar()->showMessage("调试会话已启动", 3000);
    } else {
        QMessageBox::warning(this, "警告", "无法启动调试器");
    }
}, QKeySequence(Qt::Key_F5));

debugMenu->addAction("停止调试(&T)", this, [this]() {
    debugger->stop();
    statusBar()->showMessage("调试会话已停止", 3000);
}, QKeySequence(Qt::Key_Shift | Qt::Key_F5));

debugMenu->addAction("继续(&C)", this, [this]() {
    debugger->continueExecution();
}, QKeySequence(Qt::Key_F5));

debugMenu->addAction("单步跳过(&O)", this, [this]() {
    debugger->stepOver();
}, QKeySequence(Qt::Key_F10));

debugMenu->addAction("单步进入(&I)", this, [this]() {
    debugger->stepInto();
}, QKeySequence(Qt::Key_F11));

debugMenu->addAction("单步跳出(&U)", this, [this]() {
    debugger->stepOut();
}, QKeySequence(Qt::Key_Shift | Qt::Key_F11));

// 连接调试器信号
connect(debugger, &DebuggerInterface::paused, 
        this, [this](const QString &file, int line) {
    // 打开文件并高亮显示当前行
    CodeEditor *editor = createEditor();
    editor->loadFile(file);
    
    QTextCursor cursor(editor->document()->findBlockByNumber(line - 1));
    editor->setTextCursor(cursor);
    editor->centerCursor();
    
    statusBar()->showMessage(QString("在 %1:%2 暂停").arg(file).arg(line), 3000);
});

connect(debugger, &DebuggerInterface::output, 
        this, [this](const QString &message) {
    // 在输出窗口中显示调试信息
    qDebug() << "Debugger:" << message;
});

connect(debugger, &DebuggerInterface::error, 
        this, [this](const QString &message) {
    statusBar()->showMessage("调试错误: " + message, 5000);
});

// 修改构建菜单
buildMenu->addAction("编译(&C)", this, [this]() {
    if (currentEditor) {
        QString fileName = currentEditor->currentFile();
        if (fileName.isEmpty()) {
            statusBar()->showMessage("请先保存文件", 3000);
            return;
        }
        
        QFileInfo fileInfo(fileName);
        QString suffix = fileInfo.suffix().toLower();
        
        CompilerManager::Language lang = CompilerManager::CPP;
        if (suffix == "c") lang = CompilerManager::C;
        else if (suffix == "js") lang = CompilerManager::JavaScript;
        else if (suffix == "ts") lang = CompilerManager::TypeScript;
        else if (suffix == "py") lang = CompilerManager::Python;
        
        if (!compilerManager->hasCompiler(lang)) {
            statusBar()->showMessage("没有找到对应的编译器", 3000);
            return;
        }
        
        statusBar()->showMessage("正在编译...");
        compilerManager->compile(fileName, lang);
    }
}, QKeySequence(Qt::CTRL | Qt::Key_R));

// 连接编译器信号
connect(compilerManager, &CompilerManager::compilationFinished, 
        this, [this](bool success, const QString &output) {
    if (success) {
        statusBar()->showMessage("编译成功", 3000);
    } else {
        statusBar()->showMessage("编译失败", 3000);
    }
    
    // 显示输出窗口
    QDialog outputDialog(this);
    outputDialog.setWindowTitle("编译输出");
    outputDialog.resize(600, 400);
    
    QVBoxLayout *layout = new QVBoxLayout(&outputDialog);
    QTextEdit *textEdit = new QTextEdit(&outputDialog);
    textEdit->setPlainText(output);
    textEdit->setReadOnly(true);
    layout->addWidget(textEdit);
    
    QPushButton *closeButton = new QPushButton("关闭", &outputDialog);
    connect(closeButton, &QPushButton::clicked, &outputDialog, &QDialog::accept);
    layout->addWidget(closeButton);
    
    outputDialog.exec();
});
// 在构建菜单中添加打包选项
buildMenu->addSeparator();
buildMenu->addAction("打包项目(&P)...", this, [this]() {
    if (!projectManager->isProjectOpen()) {
        QMessageBox::warning(this, "警告", "请先打开一个项目");
        return;
    }
    
    QDialog dialog(this);
    dialog.setWindowTitle("打包项目");
    dialog.resize(400, 300);
    
    QVBoxLayout *layout = new QVBoxLayout(&dialog);
    
    QLabel *label = new QLabel("选择打包格式:", &dialog);
    layout->addWidget(label);
    
    QComboBox *formatCombo = new QComboBox(&dialog);
    formatCombo->addItem("Windows安装程序", Packager::WindowsInstaller);
    formatCombo->addItem("macOS应用程序包", Packager::MacOSBundle);
    formatCombo->addItem("Linux AppImage", Packager::LinuxAppImage);
    formatCombo->addItem("便携式ZIP包", Packager::PortableZip);
    layout->addWidget(formatCombo);
    
    QTextEdit *logView = new QTextEdit(&dialog);
    logView->setReadOnly(true);
    layout->addWidget(logView);
    
    QPushButton *packageButton = new QPushButton("开始打包", &dialog);
    layout->addWidget(packageButton);
    
    Packager *packager = new Packager(&dialog);
    connect(packager, &Packager::logMessage, logView, &QTextEdit::append);
    connect(packager, &Packager::packagingFinished, &dialog, [&dialog](bool success) {
        QMessageBox::information(&dialog, "打包完成", 
                               success ? "打包成功" : "打包失败");
    });
    
    connect(packageButton, &QPushButton::clicked, &dialog, [&]() {
        Packager::PackageFormat format = static_cast<Packager::PackageFormat>(
            formatCombo->currentData().toInt());
        packager->packageProject(projectManager->projectPath(), format);
    });
    
    dialog.exec();
});
}


void MainWindow::createToolBars() {
    // TODO: 实现工具栏
}




void MainWindow::createStatusBar() {
    statusBar()->showMessage("就绪");
}

CodeEditor* MainWindow::createEditor() {
    CodeEditor *editor = new CodeEditor(this);
    int index = tabWidget->addTab(editor, "未命名");
    tabWidget->setCurrentIndex(index);
    currentEditor = editor;
    
    connect(editor, &CodeEditor::fileNameChanged, this, [this, editor](const QString &fileName) {
        int index = tabWidget->indexOf(editor);
        if (index != -1) {
            QString title = fileName.isEmpty() ? "未命名" : QFileInfo(fileName).fileName();
            tabWidget->setTabText(index, title);
        }
    });
    
    connect(tabWidget, &QTabWidget::tabCloseRequested, this, [this](int index) {
        QWidget *widget = tabWidget->widget(index);
        if (widget == currentEditor) {
            currentEditor = nullptr;
        }
        widget->deleteLater();
        tabWidget->removeTab(index);
    });
    
    return editor;
}


